import { defineStore } from "pinia";
import { RangeDownload } from "../../api/download";
// @ts-ignore
import { ElMessage, ElMessageBox } from "element-plus";
import { FileItf, OnListener } from "@/interface";
import { saveFile } from "@/util/utils";

interface DownloadItf {
    process: number;
    filename: string;
    isFinished: boolean;
    time: number;
    path: string;
    blob: string;
    fromFinish: boolean;
    isDownloading: boolean;
}

export const downloadStore = defineStore("download", {
    persist: true,
    state() {
        let tasksProcess: {
            [prop: string]: {
                process: number;
                filename: string;
                isFinished: boolean;
                isDownloading: boolean;
                time: number;
                id: number;
                blob: Blob[];
                file: FileItf;
            };
        } = {};
        let works: {
            [prop: string]: Worker;
        } = {};
        return {
            tasksProcess, //下载任务
            works,
        };
    },
    actions: {
        async download(file: FileItf) {
            let { relativePath } = file;
            if (this.tasksProcess[relativePath] && !this.tasksProcess[relativePath].isFinished) {
                ElMessage.error("当前任务已存在，请耐心等待");
                return;
            }
            if (this.tasksProcess[relativePath] && this.tasksProcess[relativePath].isFinished) {
                try {
                    await ElMessageBox.confirm("当前任务已经下载过了，确认还需要下载吗", "注意", {
                        confirmButtonText: "确认",
                        cancelButtonText: "取消",
                        type: "warning",
                    });
                } catch (error) {
                    return;
                }
            }

            let that = this;
            let onListener: OnListener = {
                onProcess(current, total) {
                    that.tasksProcess[relativePath].process = Math.floor((current / total) * 100);
                    that.tasksProcess[relativePath].isDownloading = true;
                },
                onStart(fileName) {
                    that.tasksProcess[relativePath] = {
                        process: 0,
                        filename: fileName,
                        isFinished: false,
                        time: 0,
                        id: file.id,
                        isDownloading: true,
                        blob: [],
                        file,
                    };
                },
                onFinished(time) {
                    that.tasksProcess[relativePath].time = time;
                    that.tasksProcess[relativePath].isFinished = true;
                },
                onCanceled() {
                    that.tasksProcess[relativePath].isFinished = false;
                    that.tasksProcess[relativePath].isDownloading = false;
                },
            };
            const rangeDownload = new RangeDownload(file, onListener);
            let blob = await rangeDownload.rangeDownLoadApi();
            console.log(blob);
        },

        async webWorkDownload(file: FileItf) {
            if (!this.works[file.relativePath]) {
                this.works[file.relativePath] = new Worker(new URL("../../webWork/webWork.ts", import.meta.url), {
                    type: "module",
                });
            }
            const saveWorker = this.works[file.relativePath];
            saveWorker.onmessage = (event: any) => {
                let data = event.data as DownloadItf;
                this.tasksProcess[file.relativePath] = event.data;
                this.tasksProcess[file.relativePath].file = file;
                if (data.fromFinish) {
                    saveFile(data.blob, data.filename);
                }
            };
            saveWorker.postMessage({
                file: JSON.stringify(file),
                authorization: localStorage.getItem("token"),
            });
        },
        async stopWebWorkDownload(file: FileItf) {
            const saveWorker = this.works[file.relativePath];
            saveWorker.postMessage({ stop: true });
        },

        deleteDownLoad(file: FileItf) {
            ElMessageBox.confirm("取消下载之前下载的数据将丢失，您确定要取消该下载吗?", "警告", {
                confirmButtonText: "确认",
                cancelButtonText: "关闭",
                type: "warning",
            })
                .then(() => {
                    if (this.tasksProcess[file.relativePath].isDownloading) {
                        this.stopWebWorkDownload(file);
                    }
                    // @ts-ignore
                    this.tasksProcess[file.relativePath] = null;
                    delete this.tasksProcess[file.relativePath];
                    delete this.works[ file.relativePath ]
                })
                .catch(() => {});

            // this.works[file.relativePath] = null
        },
    },
});
